package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import db.ImbiConnection;

import model.Contact;
import model.UserAccount;
import util.Log;
import validator.ContactValidator;
import web.JSONMessage;

public class ContactController extends HttpServlet{

	
	private static final long serialVersionUID = 1L;
	
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){		
			if(request.getParameter("delete")!= null){
				deleteContact(request, response);
			} else insertContact(request, response);
		}
	}


	private void deleteContact(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try{
			int id = Integer.parseInt(request.getParameter("id"));			
			ImbiConnection.getContactDAO().delete(new Contact(id, 0,0,"",0,0,""));
			response.getWriter().write(JSONMessage.message("Contact deleted"));
			Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" deleted contact "+id);
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Illegal parameters"));
		}		
	}


	private void insertContact(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		ContactValidator validator = new ContactValidator(
			"0",
			request.getParameter("contact_subject"),
			request.getParameter("contact_subjecttype"),
			request.getParameter("contact_type"),
			request.getParameter("contact_text"),
			request.getParameter("contact_note"),
			request.getParameter("contact_order")
		);
		if(validator.isValid()){
			Contact c = new Contact(
				0,
				validator.getSubject(),
				validator.getType(), 
				validator.getText(),
				validator.getOrder(),
				validator.getSubjectType(),
				validator.getNote()					
			);
			ImbiConnection.getContactDAO().insert(c);
			response.getWriter().write(JSONMessage.message("Contact added"));
			Log.write(((UserAccount) request.getSession().getAttribute("user"))
				.getUsername()+" added contact for subject "+validator.getSubject()+" type "+validator.getSubjectType());
		} else {				
			response.getWriter().write(JSONMessage.errorMessage("Illegal parameters"));
		}
	}
	
}
